/*
 * @Author: xiaosihan
 * @Date: 2021-08-15 03:17:07
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2021-10-24 02:27:12
 */

import React from "react";
import { Vector2 } from "three";
// import * as THREE from "three";

import styles from "./Canvas.less";

interface Props { }

interface State { }

export default class Canvas extends React.Component<Props, State> {
    constructor(props: Props) {
        super(props);
    }


    declare context: CanvasRenderingContext2D;


    componentDidMount() {

        const { context: ctx } = this;

        const rotateCenter = new Vector2(0, 0);

        const center = new Vector2(512, 512);

        const point = new Vector2();

        ctx.moveTo(0, 512);

        for (let i = 0; i < 7200; i++) {

            point
                .set(-1, 0)
                .rotateAround(rotateCenter, i * (Math.PI / 180))
                .setLength(512 - (i / 36 * 2.5))
                .add(center)

            ctx.lineTo(point.x, point.y);
        }

        ctx.fillStyle = "rgb(2,100,30)";
        ctx.lineWidth = 5;
        ctx.strokeStyle = "red";
        ctx.stroke();
    }

    // 返回base64
    toImage() {
        const { context: ctx } = this;
        return ctx.canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
    }

    // 图片下载
    downimage = () => {
        const save_link = document.createElementNS("http://www.w3.org/1999/xhtml", "a") as HTMLAnchorElement;
        const event = document.createEvent("MouseEvents");
        save_link.download = new Date().getTime() + ".png";
        event.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        save_link.href = this.toImage();
        save_link.dispatchEvent(event);
    }

    render() {
        return (
            <>
                <button onClick={this.downimage} >下载</button>
                <canvas
                    width={1024}
                    height={1024}
                    className={styles.canvas}
                    ref={dom => {
                        if (dom) {
                            this.context = dom.getContext("2d") as CanvasRenderingContext2D;
                        }
                    }}
                />
            </>
        );
    }
}